import { ref } from 'vue';
import { defineStore } from 'pinia';
import { getAddressListApi, updateDefaultApi } from '@/api/user/address';
import { ElMessage } from 'element-plus';

export const useAddressStore = defineStore(
  'address',
  () => {
    const addressList: any = ref([]);
    const total = ref<number>(0);

    /*获取收货地址列表*/
    const getAddressList = async (queryParams?: any) => {
      const res: any = await getAddressListApi(queryParams);
      addressList.value = res.rows;
      total.value = res.total;
    };
    /*设置默认收货地址*/
    const setDefaultAddress = async (id: string | number, queryParams?: any) => {
      const res: any = await updateDefaultApi(id);
      if (res.code === 200) {
        ElMessage.success('设置成功');
        await getAddressList(queryParams);
      }
    };

    return {
      addressList,
      getAddressList,
      total,
      setDefaultAddress
    };
  },
  {
    persist: true //同步到本地
  }
);
